package kvoog.arkanoid.common;

import java.util.ArrayList;

import com.artemis.Component;
import com.artemis.Entity;
import com.artemis.World;
import com.artemis.managers.GroupManager;
import com.artemis.managers.PlayerManager;
import com.artemis.managers.TagManager;

public class EntityBuilder {

	private final World world;
	private ArrayList<Component> components;
	private String tag;
	private ArrayList<String> groups;
	private String player;

	public EntityBuilder(World world) {
		this.world = world;
		components = new ArrayList<Component>();
		groups = new ArrayList<String>();
		reset();
	}
	
	public void reset() {
		tag = null;
		player = null;
		components.clear();
		groups.clear();
	}
	
	public EntityBuilder addComponent(Component component) {
		components.add(component);
		return this;
	}
	
	public EntityBuilder setPlayer(String player) {
		this.player = player;
		return this;
	}
	
	public EntityBuilder setTag(String tag) {
		this.tag = tag;
		return this;
	}
	
	public EntityBuilder setGroup(String group) {
		this.groups.add(group);
		return this;
	}
	
	public Entity build() {
		Entity e = world.createEntity();

		for (int i = 0; i < components.size(); i++)
			e.addComponent(components.get(i));
		
		if (player != null)
			world.getManager(PlayerManager.class).setPlayer(e, player);
		
		if (tag != null)
			world.getManager(TagManager.class).register(tag, e);
		
		if (groups.size() > 0) {
			GroupManager groupManager = world.getManager(GroupManager.class);
			for (int i = 0; i < groups.size(); i++)
				groupManager.add(e, groups.get(i));
		}
		
		e.addToWorld();
		
		reset();
		return e;
	}
}
